package com.settle4you.module.base.controller;

import cn.hutool.core.util.URLUtil;
import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.settle4you.module.base.dao.GithubUserMapper;
import com.settle4you.module.base.po.GithubUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@Controller
public class OAuthController {
    @Autowired
    private GithubUserMapper githubUserMapper;

    @Value("${oauth.github.client-id}")
    private String githubClientId;
    @Value("${oauth.github.client-secret}")
    private String githubClientSecret;

    //http://localhost:8080/oauth/github/redirect
    @RequestMapping("/oauth/github/callback")
    public String githubCallback(String code, String state, HttpServletRequest request, HttpServletResponse response){

        String url = "https://github.com/login/oauth/access_token";

        String accessTokenStr = HttpRequest.get(url)
                .form("client_id",githubClientId)
                .form("client_secret",githubClientSecret)
                .form("code",code)
                .form("redirect_uri","http://localhost:8080/oauth/github/callback")
                .form("state",state)
                .header("Accept","application/json").execute().body();

        log.warn(accessTokenStr);
        JSONObject accessTokenObject = JSONUtil.parseObj(accessTokenStr);
        String access_token = accessTokenObject.getStr("access_token");
        String githubUserStr=HttpUtil.get("https://api.github.com/user?access_token=" + access_token);
        log.info(githubUserStr);

        try {
            GithubUser githubUser = new ObjectMapper()
                    .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false)
                    .setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE)
                    .readValue(githubUserStr,GithubUser.class);
            GithubUser oldUser = githubUserMapper.selectByPrimaryKey(githubUser.getId());
            if(oldUser!=null){
                githubUserMapper.updateByPrimaryKeySelective(githubUser);
            }else{
                githubUserMapper.insert(githubUser);
            }
            //写入COOKIE,用作自动登录凭证
            ServletUtil.addCookie(response,"login_id",githubUser.getId()+"",60*60*24*365,"/",null);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return "redirect:/";
    }
    //http://localhost:8080/oauth/github/redirect
    @RequestMapping("/oauth/github/redirect")
    public String githubRedirect(){

        String callbackUrl = URLUtil.encode("http://localhost:8080/oauth/github/callback");

        StringBuilder redirectUrl = new StringBuilder("https://github.com/login/oauth/authorize?");
        redirectUrl.append("client_id=").append(githubClientId)
                .append("&redirect_uri=").append(callbackUrl)
                .append("&scope=").append("user")
                .append("&state=").append("local_user_token")
                .append("&allow_signup=").append("true");

        return "redirect:"+redirectUrl;
    }


}
